package com.sky.utils;

import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@AllArgsConstructor
@Data
@Slf4j
public class QiNiuOSSUtil {
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String prefix;

    public String upload(MultipartFile image) {
        if (ObjectUtils.isEmpty(image)) {
            return null;
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本

        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        String originalFilename = image.getOriginalFilename();
        if(originalFilename == null) {
            return null;
        }
        String name = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            uploadManager.put(image.getInputStream(), name, upToken, null, null);
        } catch (IOException e) {
            log.info("文件上传失败：{}", e.getMessage());
            throw new BaseException(MessageConstant.UPLOAD_FAILED);
        }

        log.info("文件上传到:{}", prefix + name);

        return prefix + name;
    }


}
